package com.ld.poetry.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ld.poetry.config.AppConfigs;
import com.ld.poetry.dto.FileResDTO;
import com.ld.poetry.dao.ResourceMapper;
import com.ld.poetry.entity.ResourceConfig;
import com.ld.poetry.handle.PoetryRuntimeException;
import com.ld.poetry.service.FileUploadService;
import com.ld.poetry.service.ResourceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ld.poetry.utils.FileUploadUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.Map;
import java.util.Objects;


@Slf4j
@Service
public class ResourceServiceImpl extends ServiceImpl<ResourceMapper, com.ld.poetry.entity.Resource> implements ResourceService {
    @Resource
    private Map<String, FileUploadService> fileUploadServiceMap;
    @Resource
    private AppConfigs appConfigs;


    @Override
    public FileResDTO uploadResource(MultipartFile file, String key) throws Exception {
        //计算文件hash值，避免重复上传相同文件
        String hashCode32 = FileUploadUtils.md5HashCode32(file.getInputStream());
        com.ld.poetry.entity.Resource resource = this.getOne(new LambdaQueryWrapper<com.ld.poetry.entity.Resource>()
                .eq(com.ld.poetry.entity.Resource::getHash, hashCode32).last(" limit 1"));

        // 有相同hash的文件，需要找到配置的访问url替换未空 直接把路径返回即可
        if(Objects.nonNull(resource)){
            return new FileResDTO(hashCode32,resource.getPath());
        }

        // 没有相同hash的文件，需要上传，根据配置的上传方式，上传到指定地方，返回路径
        ResourceConfig config = appConfigs.getSelectedResourceConfig();

        FileUploadService fileUploadService = fileUploadServiceMap.get(config.getId());
        if(Objects.isNull(fileUploadService)){
            log.error("unsupported upload config,config={}",config);
            throw new PoetryRuntimeException("unsupported upload type");
        }

        String filePath = fileUploadService.upload(file, config, key);

        return new FileResDTO(hashCode32,filePath);
    }
}
